<?php

namespace Modules\Common\Models\Helpers;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\Models\Trash;
use Modules\Common\Models\TrashDetail;
use Modules\Common\Util\System;

class TrashManager
{
    public static $listening = false;
    public static $desc = '';
    public static $droppingRecords = [];


    public function __construct($record)
    {
        if (self::$listening) {
            $class = Str::after(get_class($record), 'Modules\Common\Models\\');
            self::$droppingRecords[] = ['model_name' => $class, 'pk' => $record->id];
        }
    }

    public static function startTrace(string $desc)
    {
        self::$listening = true;
        self::$desc = $desc;
    }

    public static function endTrace()
    {
        self::$listening = false;
        $eidDefault = auth('api')->user()->eid; 
        $sidDefault = auth('api')->user()->sid;
        $trash = Trash::createFromArray([
            'desc' => self::$desc,
            'status' => 1,
            'admin_name' =>auth('api')->user()->name,
            'admin_id' => auth('api')->user()->id,
            'eid' =>$eidDefault,
            'sid' => $sidDefault
        ]);
        foreach (self::$droppingRecords as $record) {
            TrashDetail::createFromArray([
                'trash_id' => $trash->id,
                'model_name' => $record['model_name'],
                'pk' => $record['pk'],
                'eid' =>$eidDefault,
                'sid' => $sidDefault
            ]);
        }
    }

    public static function recover($trash)
    {
        DB::transaction(function () use ($trash) {
            foreach ($trash->details as $detail) {
                $class = 'Modules\Common\Models\\' . $detail->model_name;
                $class::updateFromArray([
                    'id' => $detail->pk,
                    'deleted_at' => null
                ], true);
            }
            $trash->status = 2;
            $trash->save();
        });
    }


}